package com.study.ceph.connection;


import com.amazonaws.services.s3.AmazonS3;
import com.study.ceph.config.CephConfig;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.impl.BaseGenericObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

@Getter
@Slf4j
@Service
public class CephConnectionPool implements ApplicationRunner {

    @Value("${MaxTotal:200}")
    private int maxTotal;

    @Value("${MaxIdle:50}")
    private int maxIdle;

    @Value("${MinIdle:10}")
    private int minIdle;

    @Value("${MaxWaitMillis:5000}")
    private long maxWaitMillis;

    @Autowired
    private CephConfig cephConfig;

    private GenericObjectPool<AmazonS3> baseGenericObjectPool;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        init();
    }

    /**
     * 初始化
     */
    public void init() {
        GenericKeyedObjectPoolConfig<AmazonS3> config = new GenericKeyedObjectPoolConfig<>();
        //最大连接数
        config.setMaxTotal(maxTotal);
        //最大空闲连接数
        config.setMaxIdlePerKey(maxIdle);
        //最小空闲连接
        config.setMinIdlePerKey(minIdle);
        //最大等待时间
        config.setMaxWaitMillis(maxWaitMillis);

        config.setTestWhileIdle(true);
        config.setTestOnCreate(true);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        BasePooledObjectFactory basePooledObjectFactory = new CephConnectionFactory(cephConfig);
        baseGenericObjectPool = new GenericObjectPool(basePooledObjectFactory);
    }

    /**
     * 获取连接
     *
     * @return
     */
    public AmazonS3 getConnection() {
        try {
            return baseGenericObjectPool.borrowObject();
        } catch (Exception e) {
            log.error("未能获取到ceph连接对象：{}", e);
        }
        return null;
    }


    /**
     * 归还连接
     *
     * @param amazonS3
     */
    public void returnConnection(AmazonS3 amazonS3) {
        if (null != amazonS3) {
            baseGenericObjectPool.returnObject(amazonS3);
        }
    }

}
